import axios from 'axios'
import type { AxiosRequestHeaders, AxiosResponse } from 'axios'
import { message } from './index'
import useLoading from '@/hooks/loading'
import { useUserStore } from '@/store'
import { getToken } from './auth'
import isEmpty from 'lodash/isEmpty'
const { setLoading } = useLoading()
const { VITE_API_BASE_URL } = import.meta.env
const service = axios.create({
  baseURL: VITE_API_BASE_URL,
})
service.interceptors.request.use(
  async config => {
    ;(config.headers as any)['token'] = 'bearer ' + getToken()
    ;(config.headers as any)['Authorization'] = 'YWRtaW46Vm5KMkt2NWpo'

    return config
  },
  error => {
    console.log('🚀 ~ file: request.ts:39 ~ error:', error)
    Promise.reject(error)
  }
)
//http response 拦截
service.interceptors.response.use(
  async (res: any) => {
    const status = res.data.code || res.data.status
    const msg = res.data.msg
    if (status == 200 || status == 0) return Promise.resolve(res.data)
    else if (status == 401) {
      /**
       * 请求401
       */
      message({
        type: 'error',
        content: '授权已过期，请重新登录',
        cb: () => {
          useUserStore().logout()
          location.reload()
        },
      })
    }
    //5开头代表服务端错误
    else if (status >= 500 && status < 600) {
      message({
        type: 'error',
        content: msg,
      })
      return Promise.reject(new Error(msg))
    } else {
      message({
        type: 'error',
        content: msg,
      })
      return Promise.reject(new Error(msg))
    }
  },
  error => {
    message({
      type: 'error',
      content: '请求错误',
    })
    return Promise.reject(new Error(error))
  }
)

interface Response<T> {
  code: number
  data: T
  status: number
  result?: any
  msg: string
  success: boolean
}
const request = <T = any>(type: 'get' | 'post' | 'delete' | 'put', api: string, data: object, loading: boolean = type != 'get', headers?: AxiosRequestHeaders): Promise<Response<T>> => {
  if (loading) setLoading(true)
  return new Promise((resolve, reject) => {
    const query = type === 'get' ? { params: data, headers } : data
    //@ts-ignore;
    service[type](api, query, { headers })
      .then((res: AxiosResponse<Response<T>>) => resolve(Promise.resolve(res as any as Response<T>)))
      .catch((err: AxiosResponse) => reject(err))
      .finally(() => loading && setLoading(false))
  })
}
type Requestoptions = {
  url: string
  data?: any
  loading?: boolean
  headers?: any
}
/**
 * get请求
 * @param  query 请求配置
 * @param data 请求参数
 * @param  success 成功回调
 * @param  err 失败回调
 */

const get = <T = any>(
  { url, loading = false, data = {}, headers = {} }: Requestoptions,

  success?: (response: Response<T>) => void,
  err?: Function
): Promise<Response<T>> => {
  return new Promise((reslove, reject) => {
    request<T>('get', url, data, loading, headers)
      .then(res => {
        if (res.code == 200 || res.status == 0) {
          success?.(res)
          reslove(res)
        } else {
          message({
            type: 'error',
            content: res.msg,
          })
          err?.(res)
          reject(res)
        }
      })
      .catch(res => {
        console.log(res)

        err?.({ msg: res.message })
        reject({ msg: res.message })
      })
  })
}

const post = <T = any>(
  { url, loading = true, data = {}, headers = {} }: Requestoptions,

  success?: (response: Response<T>) => void,
  err?: Function
): Promise<Response<T>> => {
  return new Promise((reslove, reject) => {
    request<T>('post', url, data, loading, headers)
      .then(res => {
        if (res.code == 200) {
          success?.(res)
          reslove(res)
        } else {
          message({
            type: 'error',
            content: res.msg,
          })
          err?.(res)
          reject(res)
        }
      })
      .catch(res => {
        console.log(res)

        err?.({ msg: res.message })
        reject({ msg: res.message })
      })
  })
}

export { get, post, request, service }
